var express = require('express');
var router = express.Router();
var User = require('../models/user');
/* GET users listing. */
router.get('/', function(req, res, next) {
  let _page = req.query._page,
      _limit = req.query._limit;
  User.find({}).skip((_page-1) * _limit).limit(_limit).exec(queryCb)
  function queryCb(err,docs){
    if(err){
      console.trace(err)
    }
    var data = [];
    data = docs.map(doc=>{
      return {
        id:doc._id,
        name:doc.name,
        email:doc.email,
        website:doc.website
      }
    })
    User.count({},(err,total)=>{
      if(err){
        console.trace(err)
      }
      res.send({list:data,total:total,page:_page});
    })
  }
});
router.post('/',function(req,res,next){
  let _user = null;
  if(req.body){
    _user = new User(JSON.parse(req.body));
    _user.save();
    res.send({code:200,msg:'create user success'})
  }
})
router.delete('/:id',function(req,res,next){
  let _id = req.params.id;
  if(_id){
    User.remove({_id},function(err){
      if(err){
        console.trace(err);
      }
      res.send({code:200,msg:'remove user sucess'})
    })
  }
})
router.patch('/:id',(req,res,next)=>{
  let _id = req.params.id,body = JSON.parse(req.body);
  if(_id){
    User.update({_id},body,function(err){
      if(err){
        console.trace(err)
      }
      res.send({code:200,msg:'edit user success!'});
    })
  }
})
module.exports = router;
